package com.tarena.util.datasource;

import java.sql.Statement;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnection {
	private static String url;
	private static String user;
	private static String password;
	static{
		Properties props = new Properties();
		//注册驱动
		try {
			//读取配置文件
			InputStream is = new FileInputStream("src/db.properties");
			//BufferedReader is = new BufferedReader(new FileReader("src/db.properties"));
			//把io流读取文件放入集合中
			props.load(is);
			//在Properties集合中获取属性文件中的信息
			url=props.getProperty("url");
			user=props.getProperty("user");
			password=props.getProperty("password");
			//注册驱动
			Class.forName(props.getProperty("driver"));
		} catch (ClassNotFoundException e) {  
			e.printStackTrace();
			//计写日志log4j
			throw new RuntimeException("注册驱动有误！");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException("配置文件未找到！");
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("读取配置文件失败！");
		}
	}
	/**
	 * 获取连接
	 */
	public static Connection getConnection() throws Exception{
		Connection conn = null;
		try {
			conn=DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("连接失败！");
		}
		return conn;
	}
	
	/**
	 * 关闭有结果集（增加，删除，修改）
	 * @param rs
	 * @param statement
	 * @param conn
	 * @throws Exception
	 */
	public static void close(ResultSet rs,Statement statement,Connection conn) throws Exception{
		try {
			if(rs!=null){
				rs.close();
			}
			if (statement!=null) {
				statement.close();
			}
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("关闭失败");
		}
	}
	
	/**
	 * 关闭无结果集（查询）
	 * @param statement
	 * @param conn
	 * @throws Exception
	 */
	public static void close(Statement statement,Connection conn) throws Exception{
		try {
			if (statement!=null) {
				statement.close();
			}
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("关闭失败");
		}
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(DBConnection.getConnection());
	}
}
